package com.darryring.libcore.android.task;

import android.app.Application;
import android.os.Handler;

import com.darryring.libcore.task.Task;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by hljdrl on 15/12/11.
 */
public class AndroidTask implements Task{

    private String TAG="AndroidTask";

    private Handler mUiHandler = null;

    ExecutorService fixedThreadPool;

    public AndroidTask(Application _app){
        mUiHandler = new Handler(_app.getMainLooper());
        int _cpuCount =2;
        try {
            _cpuCount = Runtime.getRuntime().availableProcessors();
        }catch(Exception ex){
            ex.printStackTrace();;
            _cpuCount = 2;
        }catch(Error error){
            error.printStackTrace();
            _cpuCount = 2;
        }
        fixedThreadPool = Executors.newFixedThreadPool(_cpuCount*2);
    }
    /**
     * @param _run
     */
    @Override
    public void postTask(Runnable _run) {
        fixedThreadPool.execute(_run);
    }
    /**
     * @param _run
     */
    @Override
    public void postUiTask(Runnable _run) {
        mUiHandler.post(_run);
    }
    @Override
    public void postUiTaskAsDelayed(Runnable _run,long delayed){
        mUiHandler.postDelayed(_run,delayed);
    }
    /**
     *
     */
    @Override
    public void shutdownTask() {
        fixedThreadPool.shutdown();
        fixedThreadPool = null;
        mUiHandler = null;
    }

}
